package com.book.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.book.api.RankingApi;
import com.book.mapper.ScoreDao;
import com.book.pojo.Score;
import com.book.service.ScoreService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author cxy
 * @since 2023-10-13 10:29:15
 */
@Service
public class ScoreServiceImpl extends ServiceImpl<ScoreDao, Score> implements ScoreService {
    @Autowired
    private ScoreDao scoreDao;
    @Autowired
    private RankingApi collectRankingApi;

    @Override
    public int insertScore(Score score) {
        Long readerId = score.getReaderId();
        //同一个读者不能对同一本书进行重复评分
        List<Score> scores = scoreDao.selectListByReaderId(readerId);
        for (Score score1 : scores) {
            Long bookId = score1.getBookId();
            if (bookId==score.getBookId()){
                return 1;
            }
        }
        scoreDao.insert(score);
        //读者对一本书进行评分 重新对这本书进行平均值计算
        Long bookId = score.getBookId();
        Score scoreaverage = scoreDao.Scoreaverage(bookId);
        collectRankingApi.deleteByBookId(bookId);
        collectRankingApi.add(scoreaverage.getBookId(),scoreaverage.getScoreAvg());
        return 2;
    }

    @Override
    public void updateScore(Score score) {
        scoreDao.updateById(score);
        Long bookId = score.getBookId();
        collectRankingApi.deleteByBookId(bookId);
        Score scoreaverage = scoreDao.Scoreaverage(bookId);
        collectRankingApi.add(scoreaverage.getBookId(),scoreaverage.getScoreAvg());

    }

    @Override
    public List<Score> ScoreRanking() {
        List<Score> scores = scoreDao.ScoreRanking();
        for (Score score : scores) {
            collectRankingApi.add(score.getBookId(),score.getScoreAvg());
        }
        return scores;
    }
}
